package br.ucb.modelo.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import br.ucb.exceptions.PersistenceException;
import br.ucb.modelo.negocio.Bazar;
import br.ucb.service.Servicos;

public class BazarDAO {
	public int insert(Long idUser) throws PersistenceException {
		String sql = "insert into bazarUsuario(idUser) values(?)";
		Connection con;
		PreparedStatement stmt;
		int linhas = 0;
		try {
			con = ConnectionFactory.getConnection();
			stmt = con.prepareStatement(sql);
			stmt.setLong(1, idUser);
			linhas = stmt.executeUpdate();
			stmt.close();
			ConnectionFactory.close();
		} catch(SQLException e) {
		  	ConnectionFactory.close();
			e.printStackTrace();
			throw new PersistenceException();
		}
		return linhas;
	}
	
	public int delete(Long idUser) throws PersistenceException {
		String sql = "delete from bazarUsuario where idUser=?";
		Connection con;
		int linhas = 0;
		PreparedStatement stmt;
		try {
			con = ConnectionFactory.getConnection();
			stmt = con.prepareStatement(sql);
			stmt.setLong(1, idUser);
			linhas = stmt.executeUpdate();
			stmt.close();
			ConnectionFactory.close();
		} catch(SQLException e) {
		  	ConnectionFactory.close();
			e.printStackTrace();
			throw new PersistenceException();
		}
		return linhas;
	}
	
	public Bazar findById(Long idUser) throws PersistenceException {
		String sql = "select * from bazarUsuario where idUser=?";
		Connection con;
		Bazar bazar = null;
		PreparedStatement stmt;
		try {
			con = ConnectionFactory.getConnection();
			stmt = con.prepareStatement(sql);
			stmt.setLong(1, idUser);
			ResultSet rs = stmt.executeQuery();
			if(rs.first())
				bazar = Servicos.putBazar(rs);
			stmt.close();
			ConnectionFactory.close();
		} catch(SQLException e) {
		  	ConnectionFactory.close();
			e.printStackTrace();
			throw new PersistenceException();
		}
		return bazar;
	}
	
}
